package cn.itsource.pethome.user.controller;

import cn.itsource.pethome.basic.constant.PetHomeConstant;
import cn.itsource.pethome.basic.util.Result;
import cn.itsource.pethome.user.domain.dto.UserDto;
import cn.itsource.pethome.user.service.IWechatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Controller
@RequestMapping("/wechat")
public class WechatController {

    @Autowired
    IWechatService wechatService;
    /**
     *申请授权码的方法
     * @return
     */
    @GetMapping("/toRequestCode")
    public String toRequestCode(){
        return "redirect:"+PetHomeConstant.CODEURL.replace("APPID", PetHomeConstant.APPID)
                .replace("REDIRECT_URI", PetHomeConstant.REDIRECT_URI);
    }

    /**
     *回调接口 将code传到门户页面
     * @param code
     * @return
     */
    @RequestMapping("/callback")
    public String callback(String code) {
        //跳转到门户网站callback.html页面，在此页面发送ajax请求获取token
        return "redirect:http://localhost:8082/callback.html?code=" + code;
    }

    /**
     * 在门户页面发送请求 去获得token 再通过token获得资源
     * @return
     */
    @PostMapping("/handleCallBack")
    @ResponseBody
    public Result handleCallBack(@RequestBody Map<String,String> param){
        try {
            //获取code授权码
            String code = param.get("code");
            //通过code获取token
            Map<String,Object> map = wechatService.handleCallBack(code);
            return new Result().setResultObj(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, e.getMessage());
        }
    }
    @PostMapping("/binder")
    @ResponseBody
    public Result binder(@RequestBody UserDto userDto){

        try {
            Map<String,Object> map = wechatService.binder(userDto);
            return new Result().setResultObj(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, e.getMessage());
        }
    }


}
